//
//  WBNewFeatureView.swift
//  WeiBoApp
//
//  Created by James on 2017/7/13.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {
    
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBOutlet weak var enterButon: UIButton!
    
    
    class func newFeatureView()->WBNewFeatureView {
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0]
        
        return v as! WBNewFeatureView
    }

    
    @IBAction func enterAction() {
        removeFromSuperview()
    }
    
    
    override func awakeFromNib() {
        //添加用于滚动的试图
        let frame = UIScreen.main.bounds
        
        let count = 3
        for i in 0 ..< count {
            let imageName = "new_feature_\(i+1)"
            let iv = UIImageView(image: UIImage(named: imageName))
            
            //设置大小
            iv.frame = frame.offsetBy(dx: CGFloat(i)*frame.width, dy: 0)
            iv.backgroundColor = UIColor.clear
            scrollView.addSubview(iv)
        }
        
        
        scrollView.backgroundColor = UIColor.clear
        scrollView.delegate = self
        
        scrollView.contentSize = CGSize(width: CGFloat(count+1)*frame.width, height: frame.height)
        
        scrollView.isPagingEnabled = true
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        enterButon.isHidden = true
    }
    
    
    
}

extension WBNewFeatureView:UIScrollViewDelegate{
    //滚动到最后一屏 让试图消失
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width+0.5)
        
        print(page)
        
        if(page == scrollView.subviews.count){
            removeFromSuperview()
        }
        
        //倒数第二页显示
        enterButon.isHidden = (page != scrollView.subviews.count-1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterButon.isHidden = true
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width+0.5)
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
        

    }

}
